// 我的物联网设备的 advertise 的 uuid  2d5baa90-35a1-4345-88bc-b8f84e0fcc63

// 在需要加、解码的的文件里引入【注意替换成自己的路径】
import {
  Base64
} from '../../utils/base64';

import TextEncoder from '../../utils/miniprogram-text-encoder';
import TextDecoder from '../../utils/miniprogram-text-decoder';

const app = getApp()

// android的手机测试是大写，而黑苹果是小写 .toUpperCase()
const SERVICE_UUID = "2D5BAA90-35A1-4345-88BC-B8F84E0FCC63";

// 用于在对象数组中查找特定属性值匹配的元素。
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  if (!buffer || buffer.length <= 0) {
    return "";
  }
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  data: {

    isShowBack: true,
    isShowHome: true,
    titleColor: '#ffffff',
    background: 'linear-gradient(135deg, #ff705d 0%, #d81e06 100%)',
    title: '蓝牙通信测试',


    discoveryStarted: false, // 是不是正在扫描

    connected: false, // 是不是连接上了？

    devices: [],
    connected: false,
    chs: [],
  },


  ////////////////////////////////////////////

  // 测试中文
  testString() {
    let msg = 'Hello中文';
    let encodeStr = Base64.encode(msg); //加密
    console.log(encodeStr);
    let decodeStr = Base64.decode(encodeStr); //解码
    console.log(decodeStr);
    // https://developers.weixin.qq.com/community/develop/doc/000ca85023ce78c8484e0d1d256400
    const encoder = new TextEncoder();
    const encodedData = encoder.encode(msg);
    console.log(encodedData)
    const hexString = ab2hex(encodedData)

    console.log(hexString)
    let china_str = new TextDecoder().decode(encodedData)

    console.log("china_str = ", china_str)
  },

  hexToUtf8(hexString) {
    // 移除十六进制字符串中的空格（如果存在）
    hexString = hexString.replace(/\s+/g, '');

    // 将十六进制字符串转换为 Uint8Array
    const bytes = new Uint8Array(hexString.length / 2);
    for (let i = 0; i < hexString.length; i += 2) {
      bytes[i / 2] = parseInt(hexString.substr(i, 2), 16);
    }

    // 使用 TextDecoder 将字节数组解码为 UTF-8 字符串
    const decoder = new TextDecoder('utf-8');
    return decoder.decode(bytes);
  },


  generateUUID: function () {
    return '1xxxxxxx-2xxx-3xxx-4xxx-5xxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  },

  generate4UUID: function () {
    return 'xxxx'.replace(/[xy]/g, function (c) {
      let r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  },

  // 连接所有的
  update() {

  },

  ////////////////////////////////////////////

  // 开始扫描 按钮
  openBluetoothAdapter() {
    console.log('打开BluetoothAdapter...');

    wx.openBluetoothAdapter({ // 初始化蓝牙模块。iOS 上开启主机/从机（外围设备）模式时需分别调用一次，并指定对应的 mode。      
      success: (res) => {
        console.log('打开BluetoothAdapter成功...')
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log('scan failed', res);
        if (res.errMsg.includes('already opened')) {
          console.log('扫描失败，重启BluetoothAdapter');
          this.restartBluetoothAdapter();
          return;
        }
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },

  // getBluetoothAdapterState() {
  //   wx.getBluetoothAdapterState({
  //     success: (res) => {
  //       console.log('getBluetoothAdapterState', res)
  //       if (res.discovering) {
  //         this.onBluetoothDeviceFound()
  //       } else if (res.available) {
  //         this.startBluetoothDevicesDiscovery()
  //       }
  //     }
  //   })
  // },

  // 

  startBluetoothDevicesDiscovery() {
    if (this.data.discoveryStarted) {
      return;
    }
    // 设置为discoveryStarted 为true
    this.setData({
      discoveryStarted: true
    })

    // 开始扫描
    wx.startBluetoothDevicesDiscovery({
      services: [SERVICE_UUID],
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)

        this.onBluetoothDeviceFound();
        // 监听发现的设备
        // this.onDeviceFoundCallback = this._onDeviceFound.bind(this);
        // wx.onBluetoothDeviceFound(this.onDeviceFoundCallback);

        // 5秒后自动停止扫描
        setTimeout(() => {
          console.log("停止扫描 try");
          this.stopBluetoothDevicesDiscovery();
        }, 5000); // 5秒 = 5000毫秒

      },
      fail: (res) => {
        console.log('startBluetoothDevicesDiscovery fail: ', res);
        this.setData({
          discoveryStarted: false
        });
      },
      complete: (res) => {
        console.log('startBluetoothDevicesDiscovery complete: ', res);
        this.setData({
          discoveryStarted: false
        });
      },
    })
  },

  // 停止发现
  stopBluetoothDevicesDiscovery() {
    console.log("停止扫描 try", !this.data.discoveryStarted);
    if (!this.data.discoveryStarted) {
      return;
    }

    console.log('停止扫描...')
    // wx.stopBluetoothDevicesDiscovery()
    wx.stopBluetoothDevicesDiscovery({
      success: (res) => {
        console.log("已停止扫描", res);
        wx.offBluetoothDeviceFound(this.onDeviceFoundCallback); // 移除监听
        this.setData({
          discoveryStarted: false
        });
      },
      fail: (err) => {
        console.error("停止扫描失败", err);
      }
    });

  },

  // 把数据加入到data里面。
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        // 如果设备没有name也没有localname，就退出。
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          // 
          console.log("--- get one device ---")
          console.log(device.advertisServiceUUIDs[0])
          if (device.advertisServiceUUIDs.length > 0 && device.advertisServiceUUIDs[0].toUpperCase() == SERVICE_UUID) {
            console.log("--- device.advertisServiceUUIDs ---")
            console.log(device.advertisServiceUUIDs)
            console.log(device)
            console.log(ab2hex(device.advertisData));

            // data[`devices[${foundDevices.length}]`] = device
            this.setData({
              devices: [...this.data.devices, device]
            });
          }

        } else {
          data[`devices[${idx}]`] = device

          console.log("--- device.advertisServiceUUIDs ---")
          console.log(device.advertisServiceUUIDs)
        }
      })
    })
  },

  // 关闭蓝牙适配器
  closeBluetoothAdapter() {
    console.log('结束流程...')
    wx.closeBluetoothAdapter()
    // this._discoveryStarted = false
    // this.discoveryStarted = false
  },

  // 重新开启蓝牙适配器
  restartBluetoothAdapter() {
    // this.data.devices = [];
    this.setData({
      devices: []
    });
    wx.closeBluetoothAdapter({
      success: (res) => {
        this.openBluetoothAdapter();
      },
      fail: (res) => {
        console.log('restartBluetoothAdapter fail: ', res)
      },
    })
    // this._discoveryStarted = false
  },

  gotoDevicePage(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    const pageUrl = `../blechat/blechat?deviceId=${deviceId}&name=${name}`
    const tabUrl = 'ble/bleComm'
    console.log('goto page:', pageUrl)

    wx.navigateTo({
      url: pageUrl,
    })
    this.stopBluetoothDevicesDiscovery;
  },

  // 
  // createBLEConnection(e) {
  //   console.log('createBLEConnection...')
  //   // debugger
  //   wx.navigateTo
  //   const ds = e.currentTarget.dataset
  //   const deviceId = ds.deviceId
  //   const name = ds.name
  //   wx.createBLEConnection({
  //     deviceId,
  //     success: (res) => {
  //       console.log('建立与设备的蓝牙连接成功。。。')
  //       this.setData({
  //         connected: true,
  //         name,
  //         deviceId,
  //       })
  //       this.getBLEDeviceServices(deviceId)
  //     },
  //     fail: (err) => {
  //       console.log('建立与设备的蓝牙连接 失败:', err)
  //     }
  //   })
  //   this.stopBluetoothDevicesDiscovery()
  // },


  // closeBLEConnection() {
  //   wx.closeBLEConnection({
  //     deviceId: this.data.deviceId
  //   })
  //   this.setData({
  //     connected: false,
  //     chs: [],
  //     canWrite: false,
  //   })
  // },

  // getBLEDeviceServices(deviceId) {
  //   wx.getBLEDeviceServices({
  //     deviceId,
  //     success: (res) => {
  //       for (let i = 0; i < res.services.length; i++) {
  //         console.log('遍历services: ', res.services[i]);
  //         if (res.services[i].isPrimary) {
  //           this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
  //           return
  //         }
  //       }
  //     },
  //     fail: (err) => {
  //       console.log('getBLEDeviceServices 失败...');
  //     }
  //   })
  // },

  // // 获得service的char
  // getBLEDeviceCharacteristics(deviceId, serviceId) {
  //   wx.getBLEDeviceCharacteristics({
  //     deviceId,
  //     serviceId,
  //     success: (res) => {
  //       console.log('getBLEDeviceCharacteristics success', res.characteristics)
  //       for (let i = 0; i < res.characteristics.length; i++) {
  //         let item = res.characteristics[i]
  //         if (item.properties.read) {
  //           wx.readBLECharacteristicValue({
  //             deviceId,
  //             serviceId,
  //             characteristicId: item.uuid,
  //           })
  //         }
  //         if (item.properties.write) {
  //           this.setData({
  //             canWrite: true
  //           })
  //           this._deviceId = deviceId
  //           this._serviceId = serviceId
  //           this._characteristicId = item.uuid
  //           this.writeBLECharacteristicValue()
  //         }
  //         if (item.properties.notify || item.properties.indicate) {
  //           wx.notifyBLECharacteristicValueChange({
  //             deviceId,
  //             serviceId,
  //             characteristicId: item.uuid,
  //             state: true,
  //           })
  //         }
  //       }
  //     },
  //     fail(res) {
  //       console.error('getBLEDeviceCharacteristics', res)
  //     }
  //   })
  //   // 操作之前先监听，保证第一时间获取数据
  //   wx.onBLECharacteristicValueChange((characteristic) => {
  //     const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
  //     const data = {}
  //     if (idx === -1) {
  //       data[`chs[${this.data.chs.length}]`] = {
  //         uuid: characteristic.characteristicId,
  //         value: ab2hex(characteristic.value)
  //       }
  //     } else {
  //       data[`chs[${idx}]`] = {
  //         uuid: characteristic.characteristicId,
  //         value: ab2hex(characteristic.value)
  //       }
  //     }
  //     // data[`chs[${this.data.chs.length}]`] = {
  //     //   uuid: characteristic.characteristicId,
  //     //   value: ab2hex(characteristic.value)
  //     // }
  //     this.setData(data)
  //   })
  // },

  // writeBLECharacteristicValue() {
  //   // 向蓝牙设备发送一个0x00的16进制数据
  //   let buffer = new ArrayBuffer(1)
  //   let dataView = new DataView(buffer)
  //   dataView.setUint8(0, Math.random() * 255 | 0)
  //   wx.writeBLECharacteristicValue({
  //     deviceId: this._deviceId,
  //     serviceId: this._deviceId,
  //     characteristicId: this._characteristicId,
  //     value: buffer,
  //   })
  // },

  onReady: function () {

    // 先从storge中找到相应的数据。
    try {
      var avatars = wx.getStorageSync('avatars');

      if (avatars === undefined || avatars == "") {
        // 弹出一个对话框，让用户输入自己的名字和介绍。
        wx.showModal({
          title: '请输入用户名（最多8个字符）和介绍（最多30字符）。',
          content: '<view class="section__title">input输入框</view><input name="input" style="background - color: #FFFFFF" placeholder="请在这里输入" /><textarea style="width:100%; height:100px;" placeholder="请输入内容"></textarea>',
          confirmText: '确定',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              // 获取用户输入的文本
              const inputValue = res.content;
              console.log('用户输入的文本是：', inputValue);
            } else if (res.cancel) {
              console.log('用户点击了取消按钮');
            }
          }
        });
      }

      
    } catch (e) {
      // 捕获错误时执行的操作
    }


    // 扫描，会把discoveryStarted设置为true
    this.openBluetoothAdapter();
  },
  // 回到上一个页面。
  onBack: function () {
    wx.navigateBack({
      delta: 1
    })

  },
  // 回到首页
  onHome: function () {
    wx.switchTab({
      url: '../index/index',
    })
  },

})